package com.xm.util.old; /**
 * security.util.FileUtil.java
 * ----------------------------------------------------------
 *        author           date         version
 * ----------------------------------------------------------
 *      liu-guoping         2015-4-27        1.0.0
 * ----------------------------------------------------------
 * Copyright © 2015–2020 juchaosoft.com. All rights reserved.
 */

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

/**
 * Function： 文件工具类
 * 
 * @author liu-guoping
 * 
 *         Time：下午1:14:07
 */
public class FileUtil {
	/**
	 * 日志对象
	 */
//	private static final TraceLogger log = TraceLogger.getLogger(security.util.FileUtil.class);
	protected static final Logger log = LoggerFactory.getLogger(FileUtil.class);

	/**
	 * 路径表
	 */
	private static Map<String, String> pathMap = new HashMap<String, String>();
	/**
	 * 根目录
	 */
	private static String rootPath;

	/**
	 * 是否jar运行环境
	 */
	private static boolean isJarEnv;

	static {
		URL url = FileUtil.class.getResource("/");
		if (url == null) {
			rootPath = System.getProperty("user.dir");
			isJarEnv = true;
		}
	}

	/**
	 * 获取文件路径
	 *
	 * @param path
	 * @return
	 */
	public static String getClassPath(String path) {

		log.debug("due to process file path：path=" + path + ",rootPath=" + rootPath + ",isJarEnv=" + isJarEnv);

		String actPath = pathMap.get(path);
		if (StringUtil.isNullOrEmpty(actPath)) {

			if (StringUtil.isNullOrEmpty(rootPath)) {
				String clp = FileUtil.class.getResource("/").getPath();
				try {
					clp = URLDecoder.decode(clp, "UTF-8");
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
				if (clp != null) {
					int idx = clp.lastIndexOf("WEB-INF");
					if (idx != -1) {
						clp = clp.substring(0, idx) + "WEB-INF/classes";
					}
				}
				actPath = new File(clp, path).getPath();
			} else {
				if (isJarEnv) {
					actPath = new File(rootPath, path).getPath();
				} else {
					actPath = new File(rootPath + "WEB-INF/classes", path).getPath();
				}
			}
			pathMap.put(path, actPath);
		}

		log.debug("文件路径处理结果：" + actPath);

		return actPath;
	}

	public static void main(String[] args) {
		System.out.println(FileUtil.getClassPath("encrypt" + File.separator + "license.txt"));
	}

}
